import { ReactViewState, ReactView, reactControl, ReactViewControl } from "pao-aop-client";
import React from "react";
import { addon } from "pao-aop";
import { ListView, Modal, WhiteSpace, Toast } from "antd-mobile";
import { request } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { Row, Button, Spin, } from "antd";
import "./list.less";
import { ROUTE_PATH, encodeUrlParam } from "src/projects/app/util-tool";
const alert = Modal.alert;
/**
 * 组件：家人列表视图控件状态
 */
export interface FamilyListViewState extends ReactViewState {
    // 数据
    dataSource?: any;
    rData?: any;
    id?: any;
    family_data?: any;
    person_data?: any;
    isSelectAll?: boolean;
    select_array?: any;
    selected_id?: any;
    empty?: boolean;
    animating?: any;
}

const getDataBlob = (datas: any) => {
    const dataBlob = {};
    datas.map((item: any, index: number) => {
        dataBlob[`${index}`] = `row - ${index}`;
    });
    return dataBlob;
};

/**
 * 组件：家人列表视图控件
 */
export class FamilyListView extends ReactView<FamilyListViewControl, FamilyListViewState> {
    public lv: any = null;
    constructor(props: any) {
        super(props);
        const ds = new ListView.DataSource({
            rowHasChanged: (r1: any, r2: any) => r1 !== r2
        });
        this.state = {
            id: '',
            dataSource: ds,
            family_data: [],
            rData: [],
            isSelectAll: false,
            select_array: [],
            selected_id: '',
            empty: false,
            animating: true,
        };
    }
    componentDidMount() {
        this.setState(
            {
                animating: true,
            },
            () => {
                // 获取当前登陆人信息
                let family_data: any = [];
                let select_array = {};
                let data1: any;
                request(this, AppServiceUtility.person_org_manage_service.get_current_user_info!()!)
                    .then((data: any) => {
                        data1 = data;
                        let newdata = [{ 'id': data[0]['id'], 'relation_type_name': '本人', 'family_person': data }];
                        family_data = [...family_data, ...newdata];
                        select_array[data[0]['id']] = false;
                        this.setState({
                            id: data[0]['id'],
                            person_data: data[0],

                        });
                        // 获取当前登陆人的家属信息
                        request(this, AppServiceUtility.family_files_service.get_user_relation_ship_list!({ 'main_relation_people': data[0]['id'] })!)
                            .then((data: any) => {
                                family_data = [...data.result, ...family_data];
                                let list: any = [...data.result, ...data1];
                                const dataBlob = getDataBlob(list);
                                if (data.result.length > 0) {
                                    for (let i = 0; i < data.result.length; i++) {
                                        select_array[data.result[i]['id']] = false;
                                    }
                                }
                                console.log(family_data);
                                this.setState({
                                    animating: false,
                                    select_array,
                                    rData: dataBlob,
                                    family_data,
                                    dataSource: this.state.dataSource.cloneWithRows(dataBlob),
                                });
                            });
                    });
            }
        );
    }
    selectThis2(e: any, obj: any) {
        this.setState({
            selected_id: obj,
        });
    }
    selectThis(e: any, obj: any) {
        let { isSelectAll, select_array } = this.state;
        if (obj === 'all') {
            let newSelectArray: any = {};
            Object.keys(select_array).map((item: any) => {
                newSelectArray[item] = !isSelectAll;
            });
            this.setState({
                select_array: newSelectArray,
                isSelectAll: !isSelectAll,
            });
        } else {
            select_array[obj] = e.target.checked;
            if (e.target.checked === false) {
                isSelectAll = false;
            } else {
                isSelectAll = true;
                Object.keys(select_array).map((item: any, index: any) => {
                    if (select_array[item] === false) {
                        isSelectAll = false;
                    }
                });
            }
            this.setState({
                isSelectAll,
                select_array,
            });
        }
    }
    // 添加
    toAdd = () => {
        // alert('请选择添加方式', <Row />, [
        //     { text: '完善本人信息', onPress: () => { this.props.history!.push(ROUTE_PATH.familyFilesEditSelf + '/' + this.state.id); } },
        //     { text: '添加长者', onPress: () => { this.props.history!.push(ROUTE_PATH.familyFilesAddOlder); } },
        //     { text: '添加子女家属', onPress: () => { this.props.history!.push(ROUTE_PATH.familyFilesAddKids); } },
        //     { text: '取消', onPress: () => { return; } },
        // ]);
        alert('请选择添加方式', <div />, [
            { text: '完善本人信息', onPress: () => { this.props.history!.push(ROUTE_PATH.familyFilesEditSelf + '/' + '本人' + '&' + encodeUrlParam(JSON.stringify(this.state.person_data))); } },
            { text: '添加长者', onPress: () => { this.props.history!.push(ROUTE_PATH.familyFilesEditSelf + '/' + '长者' + '&' + encodeUrlParam(JSON.stringify(this.state.person_data))); } },
            { text: '添加子女家属', onPress: () => { this.props.history!.push(ROUTE_PATH.familyFilesEditSelf + '/' + '家属' + '&' + encodeUrlParam(JSON.stringify(this.state.person_data))); } },
            { text: '取消', onPress: () => { return; } },
        ]);
    }
    // 完善
    toEdit(obj: any) {
        console.log(obj);
        if (obj.relation_type_name === '本人') {
            this.props.history!.push(ROUTE_PATH.familyFilesEditSelf + '/' + '本人' + '&' + encodeUrlParam(JSON.stringify(this.state.person_data)));
        } else {
            this.props.history!.push(ROUTE_PATH.familyFilesEditSelf + '/' + obj.relationShip_type + '&' + obj.id + '&' + obj.relationship_type_id + '&' + encodeUrlParam(JSON.stringify(obj.family_person)));
        }
    }
    confirm() {
        // const { family_data, select_array } = this.state;
        // let params = [];
        // for (let i = 0; i < family_data.length; i++) {
        //     if (select_array[family_data[i]['id']] === true) {
        //         params.push(family_data[i]);
        //     }
        // }
        const { family_data, selected_id } = this.state;
        if (selected_id === '') {
            Toast.fail('请至少选择一项！');
            return;
        }
        let params = [];
        for (let i = 0; i < family_data.length; i++) {
            if (family_data[i]['id'] === selected_id) {
                params.push(family_data[i]);
            }
        }
        let locationState = this.props.location!.state;
        const url = locationState && locationState['url'] ? locationState['url'] : '';
        const key = locationState && locationState['key'] ? locationState['key'] : '';
        if (!url) {
            console.error('没有找到传入的路由！');
            return;
        } else {
            this.props.history!.push(url + (key ? '/' + key : ''), {
                select_family_data: params
            });
        }
        // 调用例子
        // this.props.history!.push(ROUTE_PATH.familyList, {
        //     url: ROUTE_PATH.familyFiles,
        //     key: this.state.id
        // });
        // 获取
        // this.props.location!.state.select_family_data【记得判空】
    }
    render() {
        const { family_data, selected_id, animating, empty } = this.state;
        let index = family_data.length - 1;
        const row = (rowData: any, sectionID: any, rowID: any) => {
            if (index < 0) {
                index = family_data.length - 1;
            }
            const obj = family_data[index--];
            return (
                <Row key={rowID} className={selected_id === obj['id'] ? 'family-list-section selected' : 'family-list-section'}>
                    {/* <CheckboxItem key={obj['id']} checked={this.state.select_array[obj['id']]} onChange={(e: any) => this.selectThis(e, obj['id'])}> */}
                    <Row className="family-list-class" onClick={(e: any) => this.selectThis2(e, obj['id'])}>
                        <Row className="fm-picture"><img src={obj['family_person'] && obj['family_person'][0] && obj['family_person'][0]['personnel_info'] && obj['family_person'][0]['personnel_info']['picture_list'] ? obj['family_person'][0]['personnel_info']['picture_list'] : 'http://img.qqzhi.com/uploads/2019-01-31/053142481.jpg'} /></Row>
                        <Row className="fm-name">{obj['family_person'] && obj['family_person'][0] && obj['family_person'][0]['name'] ? obj['family_person'][0]['name'] : ''}</Row>
                        <Row className="fm-relation">{obj.relation_type_name || ''}</Row>
                        <Row className="fm-edit"><Button type="primary" onClick={() => this.toEdit(obj)}>完善</Button></Row>
                    </Row>
                    <Row className="family-list-address">
                        常用地址：{obj['family_person'] && obj['family_person'][0] && obj['family_person'][0]['personnel_info'] && obj['family_person'][0]['personnel_info']['address'] ? obj['family_person'][0]['personnel_info']['address'] : '暂无'}
                    </Row>
                    {/* </CheckboxItem> */}
                </Row>
            );
        };
        return (
            <Row>
                <Row className="family-list-add">
                    <span>选择家庭人员</span>
                    <Button type="primary" onClick={() => this.toAdd()}>添加</Button>
                </Row>
                <Row className="family-list-class">
                    {/* <CheckboxItem key={'000'} checked={this.state.isSelectAll} onChange={(e: any) => this.selectThis(e, 'all')}> */}
                    <Row className="family-list-class">
                        <Row className="fm-picture">头像</Row>
                        <Row className="fm-name">名字</Row>
                        <Row className="fm-relation">关系</Row>
                        <Row className="fm-edit">操作</Row>
                    </Row>
                    {/* </CheckboxItem> */}
                </Row>
                {family_data && family_data.length > 0 ? <Row>
                    <ListView
                        ref={el => this.lv = el}
                        dataSource={this.state.dataSource}
                        renderRow={row}
                        useBodyScroll={true}
                    />
                    <Row className="family-list-confirm">
                        <Button type="primary" style={{ width: '100%', height: '40px', }} onClick={() => this.confirm()}>确定</Button>
                    </Row>
                </Row> : null}
                {animating ? <Row>
                    <WhiteSpace size="lg" />
                    <Row style={{ textAlign: 'center' }}>
                        <Spin size="large" />
                    </Row>
                    <WhiteSpace size="lg" />
                </Row> : null}
                {empty ? <Row>
                    <WhiteSpace size="lg" />
                    <Row className='tabs-content' type='flex' justify='center'>{family_data && family_data.length ? '已经是最后一条了' : '无数据'}</Row>
                    <WhiteSpace size="lg" />
                </Row> : null}
            </Row >
        );
    }
}

/**
 * 组件：家人列表视图控件
 * 控制家人列表视图控件
 */
@addon('FamilyListView', '家人列表视图控件', '控制家人列表视图控件')
@reactControl(FamilyListView, true)
export class FamilyListViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}